package heima_bixiangdong.test.review3;

/**
 * @DESCRIPTION:
 * @USER: shg
 * @DATE: 2022/11/26 14:20
 */
public class DeadLockDemo {

    public static void main(String[] args) {
        // 创建两个线程任务
        ThreadTask threadTask1 = new ThreadTask(true);
        ThreadTask threadTask2 = new ThreadTask(false);

        // 开启两个线程
        Thread t1 = new Thread(threadTask1);
        Thread t2 = new Thread(threadTask2);

        t1.start();
        t2.start();
    }
}


// 定义线程任务
class ThreadTask implements Runnable {
    private boolean flag;

    public ThreadTask(boolean flag) {
        this.flag = flag;
    }

    @Override
    public void run() {
        if (flag) {
            while (true) {
                synchronized (MyLock.LOCKA) {
                    System.out.println(Thread.currentThread().getName() + "...if...locka");
                    synchronized (MyLock.LOCKB) {
                        System.out.println(Thread.currentThread().getName() + "...if...lockb");
                    }
                }
            }
        } else {
            while (true) {
                synchronized (MyLock.LOCKB) {
                    System.out.println(Thread.currentThread().getName() + "...else....lockb");
                    synchronized (MyLock.LOCKA) {
                        System.out.println(Thread.currentThread().getName() + "...else....locka");
                    }
                }
            }
        }
    }
}

// 自定义锁对象
class MyLock {
    public static final Object LOCKA = new Object();
    public static final Object LOCKB = new Object();
}
